package com.zjy.financialsystemjavafx.controller;

import com.zjy.financialsystemjavafx.model.entity.Transaction;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
import java.io.IOException;
import com.zjy.financialsystemjavafx.service.TransactionService;
import com.zjy.financialsystemjavafx.util.SessionContext;
import javafx.scene.control.TextInputDialog;
import java.time.LocalDate;
import java.util.Optional;
import com.zjy.financialsystemjavafx.model.entity.Account;
import com.zjy.financialsystemjavafx.model.entity.Category;
import com.zjy.financialsystemjavafx.service.AccountService;
import com.zjy.financialsystemjavafx.service.CategoryService;
import java.util.List;
import java.util.stream.Collectors;
import javafx.scene.control.ChoiceDialog;
import java.util.Arrays;

/**
 * 收支管理控制器
 */
public class TransactionController {

    @FXML
    private TableView<Transaction> transactionTable;

    @FXML
    private TableColumn<Transaction, Integer> idColumn;

    @FXML
    private TableColumn<Transaction, String> typeColumn;

    @FXML
    private TableColumn<Transaction, Double> amountColumn;

    @FXML
    private TableColumn<Transaction, java.time.LocalDate> dateColumn;

    @FXML
    private TableColumn<Transaction, String> accountColumn;

    @FXML
    private TableColumn<Transaction, String> categoryColumn;

    @FXML
    private TableColumn<Transaction, String> descColumn;

    @FXML
    private Button addButton;

    @FXML
    private Button editButton;

    @FXML
    private Button deleteButton;

    @FXML
    private Button backButton;

    private ObservableList<Transaction> transactionList = FXCollections.observableArrayList();
    private TransactionService transactionService;
    private AccountService accountService;
    private CategoryService categoryService;
    private int userId;

    @FXML
    private void initialize() {
        transactionService = new TransactionService();
        accountService = new AccountService();
        categoryService = new CategoryService();
        userId = SessionContext.getCurrentUser().getUserId();

        // 配置列
        idColumn.setCellValueFactory(new PropertyValueFactory<>("transactionId"));
        typeColumn.setCellValueFactory(new PropertyValueFactory<>("transactionType"));
        amountColumn.setCellValueFactory(new PropertyValueFactory<>("amount"));
        dateColumn.setCellValueFactory(new PropertyValueFactory<>("transactionDate"));
        accountColumn.setCellValueFactory(new PropertyValueFactory<>("accountName"));
        categoryColumn.setCellValueFactory(new PropertyValueFactory<>("categoryName"));
        descColumn.setCellValueFactory(new PropertyValueFactory<>("description"));

        transactionTable.setItems(transactionList);
        refreshTable();
    }

    private void refreshTable() {
        try {
            transactionList.clear();
            transactionList.addAll(transactionService.getTransactions(userId));
            System.out.println("[DEBUG] Transactions loaded: " + transactionList.size());
        } catch (Exception e) {
            e.printStackTrace();
            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setTitle("加载错误");
            alert.setHeaderText(null);
            alert.setContentText("无法加载交易数据: " + e.getMessage());
            alert.showAndWait();
        }
    }

    @FXML
    private void handleAdd(ActionEvent event) {
        try {
            // 获取账户列表和分类列表
            List<Account> accounts = accountService.getAccounts(userId);
            List<Category> categories = categoryService.getCategories(userId);
            // 选择账户
            ChoiceDialog<String> accDialog = new ChoiceDialog<>(accounts.get(0).getAccountName(),
                    accounts.stream().map(Account::getAccountName).collect(Collectors.toList()));
            accDialog.setTitle("添加交易");
            accDialog.setHeaderText(null);
            accDialog.setContentText("请选择账户：");
            Optional<String> accOpt = accDialog.showAndWait();
            if (!accOpt.isPresent()) return;
            String accName = accOpt.get();
            int accountId = accounts.stream().filter(a -> a.getAccountName().equals(accName))
                    .findFirst().orElse(accounts.get(0)).getAccountId();

            // 选择分类
            ChoiceDialog<String> catDialog = new ChoiceDialog<>(categories.get(0).getCategoryName(),
                    categories.stream().map(Category::getCategoryName).collect(Collectors.toList()));
            catDialog.setTitle("添加交易");
            catDialog.setHeaderText(null);
            catDialog.setContentText("请选择分类：");
            Optional<String> catOpt = catDialog.showAndWait();
            if (!catOpt.isPresent()) return;
            String catName = catOpt.get();
            int categoryId = categories.stream().filter(c -> c.getCategoryName().equals(catName))
                    .findFirst().orElse(categories.get(0)).getCategoryId();

            // 选择类型
            ChoiceDialog<String> typeDialog = new ChoiceDialog<>("Expense", Arrays.asList("Expense", "Income"));
            typeDialog.setTitle("添加交易");
            typeDialog.setHeaderText(null);
            typeDialog.setContentText("请选择类型：");
            Optional<String> typeOpt = typeDialog.showAndWait();
            if (!typeOpt.isPresent()) return;
            String type = typeOpt.get();

            // 输入金额
            TextInputDialog amtDialog = new TextInputDialog();
            amtDialog.setTitle("添加交易");
            amtDialog.setHeaderText(null);
            amtDialog.setContentText("请输入金额：");
            Optional<String> amtOpt = amtDialog.showAndWait();
            if (!amtOpt.isPresent()) return;
            double amount = Double.parseDouble(amtOpt.get());

            // 输入日期
            TextInputDialog dateDialog = new TextInputDialog(LocalDate.now().toString());
            dateDialog.setTitle("添加交易");
            dateDialog.setHeaderText(null);
            dateDialog.setContentText("请输入日期（YYYY-MM-DD）：");
            Optional<String> dateOpt = dateDialog.showAndWait();
            if (!dateOpt.isPresent()) return;
            LocalDate date = LocalDate.parse(dateOpt.get());

            // 输入描述
            TextInputDialog descDialog = new TextInputDialog();
            descDialog.setTitle("添加交易");
            descDialog.setHeaderText(null);
            descDialog.setContentText("请输入描述：");
            Optional<String> descOpt = descDialog.showAndWait();
            String desc = descOpt.orElse("");

            // 添加交易
            boolean ok = transactionService.addTransaction(userId, accountId, categoryId, type,
                    amount, date, desc);
            if (ok) refreshTable();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @FXML
    private void handleEdit(ActionEvent event) {
        Transaction selected = transactionTable.getSelectionModel().getSelectedItem();
        if (selected == null) {
            showSelectWarning();
            return;
        }
        try {
            // 获取账户和分类列表
            List<Account> accounts = accountService.getAccounts(userId);
            List<Category> categories = categoryService.getCategories(userId);

            // 编辑账户
            ChoiceDialog<String> accDialog = new ChoiceDialog<>(selected.getAccountName(),
                    accounts.stream().map(Account::getAccountName).collect(Collectors.toList()));
            accDialog.setTitle("编辑交易");
            accDialog.setHeaderText(null);
            accDialog.setContentText("请选择账户：");
            Optional<String> accOpt = accDialog.showAndWait();
            if (!accOpt.isPresent()) return;
            String accName = accOpt.get();
            int accountId = accounts.stream().filter(a -> a.getAccountName().equals(accName))
                    .findFirst().orElse(accounts.get(0)).getAccountId();

            // 编辑分类
            ChoiceDialog<String> catDialog = new ChoiceDialog<>(selected.getCategoryName(),
                    categories.stream().map(Category::getCategoryName).collect(Collectors.toList()));
            catDialog.setTitle("编辑交易");
            catDialog.setHeaderText(null);
            catDialog.setContentText("请选择分类：");
            Optional<String> catOpt = catDialog.showAndWait();
            if (!catOpt.isPresent()) return;
            String catName = catOpt.get();
            int categoryId = categories.stream().filter(c -> c.getCategoryName().equals(catName))
                    .findFirst().orElse(categories.get(0)).getCategoryId();

            // 编辑类型
            ChoiceDialog<String> typeDialog2 = new ChoiceDialog<>(selected.getTransactionType(),
                    Arrays.asList("Expense", "Income"));
            typeDialog2.setTitle("编辑交易");
            typeDialog2.setHeaderText(null);
            typeDialog2.setContentText("请选择类型：");
            Optional<String> typeOpt2 = typeDialog2.showAndWait();
            if (!typeOpt2.isPresent()) return;
            selected.setTransactionType(typeOpt2.get());

            // 编辑金额
            TextInputDialog amtDialog2 = new TextInputDialog(String.valueOf(selected.getAmount()));
            amtDialog2.setTitle("编辑交易");
            amtDialog2.setHeaderText(null);
            amtDialog2.setContentText("请输入金额：");
            Optional<String> amtOpt2 = amtDialog2.showAndWait();
            if (!amtOpt2.isPresent()) return;
            selected.setAmount(Double.parseDouble(amtOpt2.get()));

            // 编辑日期
            TextInputDialog dateDialog2 = new TextInputDialog(selected.getTransactionDate().toString());
            dateDialog2.setTitle("编辑交易");
            dateDialog2.setHeaderText(null);
            dateDialog2.setContentText("请输入日期（YYYY-MM-DD）：");
            Optional<String> dateOpt2 = dateDialog2.showAndWait();
            if (!dateOpt2.isPresent()) return;
            selected.setTransactionDate(LocalDate.parse(dateOpt2.get()));

            // 编辑描述
            TextInputDialog descDialog2 = new TextInputDialog(selected.getDescription());
            descDialog2.setTitle("编辑交易");
            descDialog2.setHeaderText(null);
            descDialog2.setContentText("请输入描述：");
            Optional<String> descOpt2 = descDialog2.showAndWait();
            selected.setDescription(descOpt2.orElse(""));
            // 更新交易
            boolean ok = transactionService.updateTransaction(selected, accountId, categoryId);
            if (ok) refreshTable();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @FXML
    private void handleDelete(ActionEvent event) {
        Transaction selected = transactionTable.getSelectionModel().getSelectedItem();
        if (selected == null) {
            showSelectWarning();
            return;
        }
        try {
            boolean ok = transactionService.deleteTransaction(selected.getTransactionId());
            if (ok) refreshTable();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 返回仪表盘视图
     */
    @FXML
    private void handleBack(ActionEvent event) {
        try {
            Parent root = FXMLLoader.load(getClass().getResource("/com/zjy/financialsystemjavafx/view/Dashboard.fxml"));
            Stage stage = (Stage) transactionTable.getScene().getWindow();
            stage.setTitle("个人财务管家 - 仪表盘");
            stage.setScene(new Scene(root));
            stage.show();
        } catch (IOException e) {
            e.printStackTrace();
            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setTitle("加载错误");
            alert.setHeaderText(null);
            alert.setContentText("无法加载仪表盘界面");
            alert.showAndWait();
        }
    }

    private void showSelectWarning() {
        Alert alert = new Alert(Alert.AlertType.WARNING);
        alert.setTitle("未选择");
        alert.setHeaderText(null);
        alert.setContentText("请先选择一条交易记录");
        alert.showAndWait();
    }
} 